var express = require('express');
var router = express.Router();
//导入模型
const AccountModel = require('../../models/AccountModel');

//导入中间件
const checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware');

//添加首页的路由
router.get('/', function(req, res, next) {
  //重定向到account
  res.redirect('/account');
});


//导入 shortid
const shortid = require('shortid');

//导入moment
const moment = require('moment');


//记账本的列表-使用promise
router.get('/account', checkLoginMiddleware,function(req, res, next) {
  AccountModel.find().sort({time: -1}).exec()
    .then(data => {
      res.render('list', {accounts: data, moment: moment});
    })
    .catch(err => {
      res.status(500).send('读取失败.');
    });
});



//记账本的添加
router.get('/account/create',checkLoginMiddleware, function(req, res, next) {
  res.render('create');
});

  //账本新增记录
  router.post('/account', function(req, res, next) {

    //插入数据库
    AccountModel.create({
      ...req.body,
      //将时间转换为Date对象
      time: moment(req.body.time).toDate()
    },
      res.render('success', {msg: '添加成功啦', url: '/account'})
    )
  });



//删除记账本的记录-使用promise
router.get('/account/:id',checkLoginMiddleware, (req, res)=>{
  AccountModel.deleteOne({_id:req.params.id}).exec()
    .then(data => {
      res.render('success', {msg: '成功删除文件', url: '/account'});
    })
    .catch(err => {
      res.status(500).send('删除失败.');
    });
}
);

//退出登陆
router.post('/logout', (req, res) => {
  //销毁 session
  req.session.destroy(() => {
    res.render('success', {msg: '退出成功啦', url: '/login'});
  })
});


module.exports = router;
